<?php

namespace common\handlers\backend;

use common\handlers\BaseHandler;
use yii\helpers\Json;

/**
 * 动态设置客户端主题参数
 */
class BeforeRenderDynamicUpdateViewParams extends BaseHandler
{
    const CLIENT_USER_PREFERENCE_COOKIE_NAME = 'user_preference';

    public function run($event)
    {
        /** @var \yii\web\View $sender */
        $sender = $event->sender;
        $cookieCollect = $this->request->cookies;

        if (!$this->user->isGuest) {
            //已授权用户从系统获取偏好
            $identity = $this->user->identity;
            if (!empty($identity->user_preference)) {
                $userPreference = Json::decode($identity->user_preference);
            } else {
                $userPreference = [];
            }
        } else {
            //未授权用户从客户端Cookie中获取偏好
            if ($userPreference = $cookieCollect->getValue(self::CLIENT_USER_PREFERENCE_COOKIE_NAME)) {
                $userPreference = Json::decode($userPreference);
            }
        }

        if (empty($userPreference)) {
            return;
        }

        $viewTheme = !empty($userPreference['view_theme']) ? $userPreference['view_theme'] : [];
        foreach ($viewTheme as $paramName => $paramValue) {
            $sender->params[$paramName] = $paramValue;
        }
    }
}